
#ifndef __PROCESS_POOL_HPP__
#define __PROCESS_POOL_HPP__


#include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "task.hpp"

class Channel
{
public:
    Channel(int wfd,pid_t id)
        :_wfd(wfd)
        ,_subid(id)
    {
        _name="channel-"+std::to_string(_wfd)+"-"+std::to_string(_subid);
    }

    ~Channel()
    {

    }

    int Wfd()
    {
        return _wfd;
    }

    pid_t Subid()
    {
        return _subid;
    }

    const std::string& Name()
    {
        return _name;
    }   

    //send就是向子进程写任务码
    void Send(int code)
    {
        int n=write(_wfd,&code,sizeof(code));
        (void)n;
    }

    void Close()
    {
        close(_wfd);
    }

    void wait()
    {
        int rid=waitpid(_subid,nullptr,0);
        (void)rid;
    }

private:
    int _wfd;
    pid_t _subid;
    std::string _name;
};

class ChannelManager
{
public:
    ChannelManager()
        :_next(0)
    {

    }

    ~ChannelManager()
    {

    }

    void Insert(int wfd,pid_t subid)
    {
        _channels.emplace_back(wfd,subid);
    }

    //这里采用轮询的方式控制负载均衡
    Channel& Select()
    {
        auto& c=_channels[_next];
        _next++;
        _next%=_channels.size();

        return c;

    }

    // void StopSubProcess()
    // {
    //     for(auto& e:_channels)
    //     {
    //         e.Close();
    //     }
    // }

    // void WaitSubProcess()
    // {
    //     for(auto& e:_channels)
    //     {
    //         e.wait();
    //     }
    // }

    void CloseAll()
    {
        for(auto& e:_channels)
        {
            e.Close();
        }
    }

    void CloseAndWait()
    {
        for(auto& e:_channels)
        {
            e.Close();
            std::cout<<"关闭了子进程 "<<e.Name()<<std::endl;

            e.wait();
            std::cout<<"回收了子进程 "<<e.Name()<<std::endl;
        }

        // //解决方案一：倒着回收
        // for(int i=_channels.size()-1;i>=0;i--)
        // {
        //      _channels[i].Close();
        //     std::cout<<"关闭了子进程 "<<_channels[i].Name()<<std::endl;

        //      _channels[i].wait();
        //      std::cout<<"回收了子进程 "<<_channels[i].Name()<<std::endl;
        // } 
    }

private:
    std::vector<Channel> _channels;
    int _next;
};

const int defaultprocessnum=5;

class ProcessPool
{
public:
    ProcessPool(int process_num)
        : _process_num(process_num)
    {
        _tm.Register(PrintLog);
        _tm.Register(DownLoad);
        _tm.Register(UpLoad);
    }

    ~ProcessPool()
    {

    }

    void Work(int rfd)
    {
        while(1)
        {
            int code=0;
            ssize_t n=read(rfd,&code,sizeof(code));
            if(n>0)
            {
                if(n!=sizeof(code))
                {
                    continue;
                }

                std::cout<<"子进程["<<getpid()<<"]收到一个任务码"<<code<<std::endl;

                _tm.Execute(code);
                
            }
            else if(n==0)
            {
                std::cout<<"写端关闭，子进程["<<getpid()<<"]退出"<<std::endl;
                break;
            }
            else
            {
                std::cout<<"读取失败"<<std::endl;
                break;
            }
        }
    }

    bool Start()
    {
        for(int i=0;i<_process_num;i++)
        {
            //1.创建管道
            int pipefd[2]={0};
            int n=pipe(pipefd);
            if(n<0)
            {
                return false;
            }

            //2.创建子进程
            pid_t subid=fork();
            if(subid<0)
            {
                return false;
            }
            else if(subid==0)
            {
                //解决方案2：真正让父进程一人指向所有写端，将子进程指向自己哥哥的所有写端都关闭
                _cm.CloseAll();

                close(pipefd[1]);
                Work(pipefd[0]);
                close(pipefd[0]);
                exit(0);
            }
            else 
            {
                close(pipefd[0]);
                _cm.Insert(pipefd[1],subid);
            }   
        }
        return true;
    }

    void Run()
    {   
        //1.选择一个任务
        int taskcode=_tm.Code();
        
        //2.选择一个子进程(信道)，考虑负载均衡
        auto& c=_cm.Select();
        std::cout<<"选择了子进程 "<<c.Name()<<std::endl;

        //3.发送任务
        c.Send(taskcode);
        std::cout<<"发送了任务码 "<<taskcode<<std::endl;

    }

    void Stop()
    {
        // //关闭父进程所有wfd
        // _cm.StopSubProcess();

        // //回收所有子进程
        // _cm.WaitSubProcess();

        _cm.CloseAndWait();
    }

private:
    ChannelManager _cm;
    TaskManager _tm;
    int _process_num;
};




#endif